function toCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5 / 9;
}

function toFahrenheit(celsius) {
  return (celsius * 9 / 5) + 32;
}

function tryConvert(temperature, convert) {
  const input = parseFloat(temperature);
  if (Number.isNaN(input)) {
    return '';
  }
  const output = convert(input);
  const rounded = Math.round(output * 1000) / 1000;
  return rounded.toString();
}

class Child extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      scaleNames: {
        c: 'Celsius',
        f: 'Fahrenheit'
      }
    }
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }
  render() {
    return (
      <fieldset>
        <legend>{this.state.scaleNames[this.props.scale]}</legend>
        <input value={this.props.temperature} onChange={this.handleChange} />
      </fieldset>
    )
  }
}

function BoilingVerdict(props) {
  if (props.celsius >= 100) {
    return <p>The water would boil.</p>;
  }
  return <p>The water would not boil.</p>;
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      temperature: 0, 
      scale: 'c'
    };
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
  }
  handleCelsiusChange(value){
    this.setState({
      temperature: value,
      scale: 'c'
    })
  }
  handleFahrenheitChange(value){
    this.setState({
      temperature: value,
      scale: 'f'
    })
  }  
  render() {
    const scale = this.state.scale;
    const celsius = scale === 'f' ? tryConvert(this.state.temperature, toCelsius): this.state.temperature;
    const fahrenheit = scale === 'c' ? tryConvert(this.state.temperature, toFahrenheit): this.state.temperature;
    return (
      <div>
        <h1>App: {this.state.value} </h1>
        <Child scale="c" temperature={celsius} onTemperatureChange={this.handleCelsiusChange} />
        <Child scale="f" temperature={fahrenheit} onTemperatureChange={this.handleFahrenheitChange} />
        <BoilingVerdict celsius={celsius} />
      </div>
    );
  }
}
ReactDOM.render(
  <App />,
  document.getElementById('root')
);